package com.burgeon.backend.Rest.base;
/**
 * 接口基类
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;

public abstract class RESTBase {

    private final static Log logger = LogFactory.getLog(RESTBase.class);

    /**
     * 发送数据
     * @param data
     * @return
     */

    protected static String RESULT(MultiValueMap data,String URL) throws Exception {

//        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//        requestFactory.setConnectTimeout(3000);
//        requestFactory.setReadTimeout(3000);

        RestTemplate restTemplate =new RestTemplate();


        String str = null;
        try {
            str = restTemplate.postForObject(URL, data, String.class);

        } catch (Exception e) {
            try {
                str = restTemplate.postForObject(URL, data, String.class);
            } catch (RestClientException ex) {

                throw new Exception(e.getMessage());
            }

        }
        return str;
    }

    /**
     * 必选参数
     * @param command 请求类型
     * @param params  请求参数
     * @return
     */
    protected static MultiValueMap DATA(String command, HashMap params,String ACCOUNT,String PASSWORD) {
        sipSign sipSign = new sipSign();

        String sip_timestamp = sipSign.timestamp(); //时间戳
        String sip_sign = sipSign.getMD5Password(ACCOUNT, sip_timestamp, PASSWORD); //签名

        HashMap transaction = new HashMap();

        transaction.put("command", command);

        transaction.put("params", params);

        ArrayList arrayList = new ArrayList();
        arrayList.add(transaction);

        MultiValueMap Map = new LinkedMultiValueMap();//MultiValueMap可以让一个Key对应多个值
        Map.add("sip_appkey", ACCOUNT);
        Map.add("sip_timestamp", sip_timestamp);
        Map.add("sip_sign", sip_sign);
        Map.add("transactions", String.valueOf(arrayList));

        return Map;
    }

}
